package com.zzyl.nursing.service.impl;

import java.text.DecimalFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.FamilyMemberElderDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.FamilyMemberELderVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.health.HealthDataItemVo;
import com.zzyl.nursing.vo.health.HealthDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private ElderServiceImpl elderService;

    @Autowired
    private FamilyMemberElderServiceImpl familyMemberElder;

    @Autowired
    private IFamilyMemberElderService familyMemberElderService;


    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {

        return familyMemberElderService.removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ElderServiceImpl elderServiceImpl;

    @Autowired
    private BedServiceImpl bedService;

    @Autowired
    private RoomServiceImpl roomService;

    @Autowired
    private DeviceServiceImpl deviceService;

    @Autowired
    private IDeviceDataService deviceDataService;

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 小程序端登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if (ObjectUtil.isEmpty(familyMember)) {
            familyMember = FamilyMember
                    .builder()
                    .openId(openid)
                    .build();
        }

        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(familyMember, phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("userName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);
        return loginVo;
    }


    /**
     * 小程序查询健康数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<HealthDataVo> queryServiceProperties(String iotId) {
        //1.通过设备id查询数据库中是否存在设备数据
        List<HealthDataVo> healthDataVos = new ArrayList<>();


        String deviceData = redisTemplate.opsForHash().get(CacheConstants.DEVICE_LAST_DATA, iotId).toString();
        List<DeviceData> dataList = JSONUtil.toList(deviceData, DeviceData.class);
        dataList.forEach(list -> {
            Integer dataValue = Integer.valueOf(list.getDataValue());
            String alarmTime = String.valueOf(list.getAlarmTime());
            HealthDataVo vo = new HealthDataVo();
            vo.setFunctionId(list.getFunctionId());
            vo.setEventTime(alarmTime);
            vo.setValue(dataValue);
            healthDataVos.add(vo);
        });
        return healthDataVos;
    }

    /**
     * 按天统计查询指标数据
     *
     * @param iotId
     * @param startTime
     * @param endTime
     * @param functionId
     * @return
     */
   /* @Override
    public List<HealthDataItemVo> queryDeviceDataListByDay(String iotId, Long startTime, Long endTime, String functionId) {
        // 1. 构建查询条件
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        Long timestamp = Long.parseLong(startTime.toString());
        LocalDateTime start = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(timestamp),
                ZoneId.systemDefault()
        );
        Long timestamp1 = Long.parseLong(endTime.toString());
        LocalDateTime end = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(timestamp1),
                ZoneId.systemDefault()
        );

        queryWrapper.eq(DeviceData::getIotId, iotId)
                .between(DeviceData::getAlarmTime, start, end)
                .eq(functionId != null, DeviceData::getFunctionId, functionId); // 如果 functionId 不为空，则按功能ID过滤
        // 2. 根据查询条件得到设备数据列表
        //List<DeviceData> deviceDataList = deviceDataMapper.selectList(queryWrapper);
        List<DeviceData> deviceDataList = deviceDataService.list(queryWrapper);
        System.out.println(deviceDataList);
        //4。将结果转换为 HealthDataItemVo
        List<HealthDataItemVo> result = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#.0"); // 保留1位小数（在循环外创建，避免重复初始化）
        Double dataValue;
        for (DeviceData deviceData : deviceDataList) {
            dataValue = Double.valueOf(deviceData.getDataValue());

            Double formattedValue = Double.valueOf(df.format(dataValue));
            String alarmTime = String.valueOf(deviceData.getAlarmTime());
            String substringTime = alarmTime.substring(11, 16);
            HealthDataItemVo vo = new HealthDataItemVo();
            vo.setDateTime(substringTime);
            vo.setDataValue(formattedValue);
            result.add(vo);
        }
        return result;
    }*/
    @Override
    public List<Map<String, Object>> queryDeviceDataListByDay(String iotId, Long startTime, Long endTime, String functionId) {
        Instant start = Instant.ofEpochMilli(startTime);
        Instant end = Instant.ofEpochMilli(endTime);

        start = start.atZone(ZoneId.systemDefault()).toInstant();
        end = end.atZone(ZoneId.systemDefault()).toInstant();
        //转换成字符串格式的日期格式
        String startTimes = DateUtil.format(Date.from(start), "yyyy-MM-dd HH:mm:ss");
        String endTimes = DateUtil.format(Date.from(end), "yyyy-MM-dd HH:mm:ss");

        List<Map<String, Object>> list = deviceDataMapper.queryDeviceDataListByDay(iotId, startTimes, endTimes, functionId);
        list.forEach(item -> {

            String time = (String) item.get("dateTime");
            String substring = time.substring(11, 16);
            item.put("dateTime", substring);

            Double o = (Double) item.get("dataValue");
            DecimalFormat df = new DecimalFormat("#.0"); // 保留一位小数
            String number = df.format(o);
            double parsed = Double.parseDouble(number);
            item.put("dataValue", parsed);
        });
        return list;
    }

    /**
     * 周统计查询指标数据
     *
     * @param iotId
     * @param startTime
     * @param endTime
     * @param functionId
     * @return
     */
   /* @Override
    public List<Map<String, Object>> queryDeviceDataListByWeek(String iotId, Long startTime, Long endTime, String functionId) {
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        Instant start = Instant.ofEpochMilli(startTime);
        Instant end = Instant.ofEpochMilli(endTime);

        start = start.atZone(ZoneId.systemDefault()).toInstant();
        end = end.atZone(ZoneId.systemDefault()).toInstant();

        String startTimes = DateUtil.format(Date.from(start), "yyyy-MM-dd HH:mm:ss");
        String endTimes = DateUtil.format(Date.from(end), "yyyy-MM-dd HH:mm:ss");



       *//* Long timestamp = Long.parseLong(startTime.toString());
        LocalDateTime start = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(timestamp),
                ZoneId.systemDefault()
        );
        Long timestamp1 = Long.parseLong(endTime.toString());
        LocalDateTime end = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(timestamp1),
                ZoneId.systemDefault()
        );*//*
        DecimalFormat df = new DecimalFormat("#");
        queryWrapper.eq(DeviceData::getIotId, iotId)
                .between(DeviceData::getAlarmTime, startTimes, endTimes)
                .eq(functionId != null, DeviceData::getFunctionId, functionId); // 如果 functionId 不为空，则按功能ID过滤
        // 2. 根据查询条件得到设备数据列表
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(queryWrapper);
        //4。将结果转换为 HealthDataItemVo
        List<Map<String, Object>> list = new ArrayList<>();
        Double dataValue;
        for (DeviceData deviceData : deviceDataList) {
            dataValue = Double.valueOf(deviceData.getDataValue());
            HashMap<String, Object> map = new HashMap<>();

            Double formattedValue = Double.valueOf(df.format(dataValue));
            String alarmTime = deviceData.getAlarmTime().toString();
            String substringTime = alarmTime.substring(5, 10);
            map.put("dateTime", substringTime);
            map.put("dataValue", formattedValue);
            list.add(map);
        }
        return list;
    }*/

    @Override
    public List<Map<String, Object>> queryDeviceDataListByWeek(String iotId, Long startTime, Long endTime, String functionId) {
        Instant start = Instant.ofEpochMilli(startTime);
        Instant end = Instant.ofEpochMilli(endTime);

        start = start.atZone(ZoneId.systemDefault()).toInstant();
        end = end.atZone(ZoneId.systemDefault()).toInstant();
        //转换成字符串格式的日期格式
        String startTimes = DateUtil.format(Date.from(start), "yyyy-MM-dd HH:mm:ss");
        String endTimes = DateUtil.format(Date.from(end), "yyyy-MM-dd HH:mm:ss");

        List<Map<String, Object>> list = deviceDataMapper.queryDeviceDataListByWeek(iotId, startTimes, endTimes, functionId);
        list.forEach(item -> {
            String time = item.get("dateTime").toString();
            String substring = time.substring(5, 10);
            String replace = substring.replace("-", ".");
            item.put("dateTime", replace);

            Double o = (Double) item.get("dataValue");
            DecimalFormat df = new DecimalFormat("#"); // 保留整数
            String number = df.format(o);
            double parsed = Double.parseDouble(number);
            item.put("dataValue", parsed);
        });
        return list;
    }


    /**
     * 保存或更新用户
     *
     * @param familyMember
     * @param phone
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone, 7, 11);
        familyMember.setName(nickName);
        //保存
        save(familyMember);
    }

    /**
     * 小程序端绑定老人
     *
     * @param dto
     */
    @Override
    public void add(FamilyMemberElderDto dto) {
        //添加老人姓名、身份证号、与家属的关系
        //需要校验：根据身份证号搜索老人是否存在，不存在弹窗老人未入院或老人身份证输入有误
        Elder one = elderService.getOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, dto.getIdCard()));
        if (ObjectUtil.isEmpty(one)) {
            throw new BaseException("老人身份证输入有误，未查询到该老人");
        }
        //需要校验：老人姓名与身份证号是否匹配，不匹配弹出老人姓名输入有误
        if (!Objects.equals(one.getName(), dto.getName())) {
            throw new BaseException("老人姓名输入有误");
        }
        //一切无误后将绑定加入到数据库，新建一个对象往里面装值
        FamilyMemberElder fme = new FamilyMemberElder();
        //备注里添加关系
        fme.setRemark(dto.getRemark());
        //绑定老人id
        fme.setElderId(one.getId());
        //绑定家属id
        fme.setFamilyMemberId(UserThreadLocal.getUserId());
        //绑定老师姓名
        fme.setElderName(one.getName());
        //添加到数据库
        familyMemberElder.save(fme);
    }

    /**
     * 查询家人列表
     *
     * @param familyMemberId
     * @return
     */
    @Override
    public List<FamilyMemberElder> getMyFamilyMembers(Long familyMemberId) {
        List<FamilyMemberElder> list = familyMemberElder.list(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, familyMemberId));
        return list;
    }

    /**
     * 查看家人列表（分页查询）
     *
     * @return
     */
    @Override
    public List<FamilyMemberELderVo> listByPage(Integer pageNum, Integer pageSize) {

        List<FamilyMemberELderVo> list = new ArrayList<>();

        //拿到用户的家属id
        Long familyMemberId = UserThreadLocal.getUserId();
        //通过家属id找中间表对应的集合，如果空则证明没有绑定老人
        List<FamilyMemberElder> familyMemberElderList = familyMemberElder.list(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, familyMemberId));
        if (CollUtil.isEmpty(familyMemberElderList)) {
            throw new BaseException("您还未绑定老人！");
        }

        //存在遍历该集合，并将一部分值填入vo中
        familyMemberElderList.forEach(fme -> {
            FamilyMemberELderVo vo = new FamilyMemberELderVo();
            vo.setMid(fme.getId());
            vo.setMremark(fme.getRemark());
            vo.setElderId(fme.getElderId());
            vo.setName(fme.getElderName());
            //通过vo中老人id到老人表找对应的老人，将老人中的信息加入vo中
            Elder one = elderServiceImpl.getOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getId, vo.getElderId()));
            vo.setImage(one.getImage());
            vo.setBedNumber(one.getBedNumber());
            //通过老人中床位编号bed_number找到bed中对应的床位，拿到room_id，然后在room中找房间型号
            Bed bed = bedService.getOne(Wrappers.<Bed>lambdaQuery().eq(Bed::getBedNumber, vo.getBedNumber()));
            Room room = roomService.getOne(Wrappers.<Room>lambdaQuery().eq(Room::getId, bed.getRoomId()));
            vo.setTypeName(room.getTypeName());

            //查询绑定老人的移动设备
            LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Device::getLocationType, 0);
            wrapper.eq(Device::getBindingLocation, vo.getElderId());
            Device device = deviceService.getOne(wrapper);
            //对是否有设备进行判断
            if (ObjectUtil.isEmpty(device)) {
                vo.setIotId(null);
                vo.setDeviceName(null);
                vo.setProductKey(null);
            } else {
                vo.setIotId(device.getIotId());
                vo.setDeviceName(device.getDeviceName());
                vo.setProductKey(device.getProductKey());
            }

            list.add(vo);
        });

        return list;
    }
}
